import Vue from 'vue'
import Vuex from 'vuex'
import router from './router'
import axios from 'axios'
Vue.use(Vuex)

//获取当前时间
const now = new Date();
const state = {
	// 输入的搜索值
	searchText: '',
	// 当前登录用户
    user: {
    	name: 'ratel',
    	img: 'static/images/UserAvatar.jpg',
        memberId: ''
    },
    // 对话好友列表
    chatlist: [
        
    ],
    chatGrouplist: [],
    groupList: [],
    // 当前聊天人id
    toMemberId: '',
    // 当前聊天群id
    toGroupId: '',
    // 好友列表
    friendlist: [],
    // 得知当前选择的是哪个对话
    selectId: 1,
    // 得知当前选择的是哪个对话
    selectGroupId: 1,
    selectGroupName: '',
    // 得知当前选择的是哪个好友
    selectFriend: {},
    // 得知当前选择的是哪个任务
    selectDutyId: 0,
    // 聊天模式 1 单聊 2 群聊
    model: 1
}

const mutations = {
  // 从localStorage 中获取数据
  initData(state) {
    let data = localStorage.getItem("vue-chat");
    let groupData = localStorage.getItem("vue-chat-group");
    if (data) {
      state.chatlist = JSON.parse(data);
      state.toMemberId = JSON.parse(data)[0].memberId;
    }
    if (groupData) {
      state.chatGrouplist = JSON.parse(groupData)
    }
  },
  // 获取搜索值
  search(state, value) {
    state.searchText = value;
  },
  // 得知用户当前选择的是哪个对话。便于匹配对应的对话框
  selectSession(state, value) {
    state.selectId = value;
  },
  // 得知用户当前选择的是哪个群对话。便于匹配对应的对话框
  selectGroupSession(state, value) {
    state.selectGroupId = value;
    let result = state.chatGrouplist.find(session => session.id === value);
    result.newMessage = false
  },
  // groupName
  selectGroupName(state, value) {
    state.selectGroupName = value;
  },
  // 得知用户当前选择的是哪个对话
  toMemberId(state, value) {
    state.toMemberId = value;
  },
  // 得知用户当前选择的是哪个对话
  toGroupId(state, value) {
    state.toGroupId = value;
  },
  // 好友列表
  getFriendList(state, list) {
    state.friendlist = list;
  },
  uId(state, list) {
    state.user.name = list.realName;
    state.user.memberId = list.id;
    state.user.img = list.avatar;
  },
  // 得知用户当前选择的是哪个好友的id。
  selectFriend(state, data) {
    state.selectFriend = data;
  },
  // 发送信息
  sendMessage(state, msg) {
    if (msg.type == 'friend') {
      let result = state.chatlist.find(session => session.id === state.selectId);
      result.messages.push({
        content: msg.content,
        date: new Date(),
        self: msg.flag
      });
    } else {
      let result = state.chatGrouplist.find(session => session.id === msg.id);
      if (result) {
        result.newMessage = true
        result.messages.push({
          username: msg.username,
          content: msg.content,
          date: new Date(),
          self: msg.flag
        });
      } else {
        axios.get(`/api/groupMessage/getGroupByUserId.do?memberId=${state.user.memberId}`).then(({ data }) => {
          state.groupList = data.object;
          
          let dt = data.object.find(session => session.id === msg.id);
          let obj = {
            id: msg.id,
            groupName: dt.groupName,
            newMessage: true,
            messages: [
              {
                username: msg.username,
                content: msg.content,
                date: new Date(),
                self: msg.flag
              }
            ],
          }
          state.chatGrouplist.unshift(obj)
        })
      }
      state.selectGroupId = msg.id
    }
  },
  // 改变type
  chatType(state, type) {
    state.model = type
  },
  // 获取grouplist
  groupList(state, groupList) {
    state.groupList = groupList
    
    let chatGrouplist = []
    groupList.forEach(item => {
      let result = state.chatGrouplist.find(session => session.id === item.id)
      if (result) {
        chatGrouplist.push(result)
      } else {
        let obj = {
          id: item.id,
          groupName: item.groupName,
          messages: [
          ],
        }
        chatGrouplist.push(obj)
      }
    })

    state.chatGrouplist = chatGrouplist
    
  },
  
  // 获取离线消息
  receiveOfflineMessage(state, arr) {
    axios.get(`/api/groupMessage/getGroupByUserId.do?memberId=${state.user.memberId}`).then(({ data }) => {
      state.groupList = data.object;

      arr.forEach(item => {
        if (item.type == 'friend') {
          let result = state.chatlist.find(session => session.memberId === item.id);
          if (result) {
            result.messages.push({
              content: item.content,
              date: new Date(),
              self: false
            });
          } else {
            state.chatlist.unshift({
              id: new Date().getTime(),
              memberId: item.id,
              user: {
                name: item.username,
                img: item.avatar
              },
              messages: [
                {
                  content: item.content,
                  date: new Date()
                }
              ],
              index: 1
            });
          }
        } else {
          let result = state.chatGrouplist.find(session => session.id === item.id);
          if (result) {
            result.newMessage = true
            result.messages.push({
              username: item.username,
              content: item.content,
              date: item.time,
              self: item.mine
            });
          } else {
            let dt = data.object.find(session => session.id === item.id);
            let obj = {
              id: item.id,
              groupName: dt.groupName,
              newMessage: true,
              messages: [
                {
                  username: item.username,
                  content: item.content,
                  date: new Date(),
                  self: item.mine
                }
              ],
            }
            state.chatGrouplist.unshift(obj)
          }
        }
      
      })
    })
  },
  

  // 选择好友后，点击发送信息。判断在聊天列表中是否有该好友，有的话跳到该好友对话。没有的话
  // 添加该好友的对话 并置顶
  send(state) {
    // let result = state.friendlist.find(friend => friend.id === state.selectFriendId)
    let result = state.selectFriend;
    let msg = state.chatlist.find(msg => msg.user.name === result.realName);
    if (!msg) {
      let time = new Date().getTime()
      state.selectId = time;
      // for (let i = 0; i < state.chatlist.length; i++) {
      //   state.chatlist[i].id++;
      //   state.chatlist[i].index++;
      // }
      state.chatlist.unshift({
        id: time,
        memberId: result.id,
        user: {
          name: result.realName,
          img: result.avatar
        },
        messages: [
          {
            content: "可以给我发信息啦！",
            date: new Date()
          }
        ],
        index: 1
      });
      state.toMemberId = result.id
    } else {
      state.selectId = msg.id;
      state.toMemberId = msg.memberId
    }
    router.push({ path: "/chat?open=true" });
  }
};
const getters = {
    // 筛选出含有搜索值的聊天列表
    searchedChatlist (state) {
       let sessions = state.chatlist.filter(sessions => sessions.user.name.includes(state.searchText));
       return sessions
    },
    // 筛选出含有搜索值的好友列表
    searchedFriendlist (state) {
       let friends = state.friendlist
       return friends
    },
    // 筛选出含有搜索值的任务
    searchedDutylist (state) {
       let dutys = state.dutyList.filter(dutys => dutys.remark.includes(state.searchText));
       return friends
    },
    // 通过当前选择是哪个对话匹配相应的对话
    selectedChat (state) {
      if (state.model == 1) {
        let session = state.chatlist.find(session => session.id === state.selectId);
        if (!session && state.chatlist.length > 0) {
          session = state.chatlist[0]
          state.selectId = state.chatlist[0].id
        }
        console.log(session);
        
        return session
      } else {
        let session = state.chatGrouplist.find(session => session.id === state.selectGroupId);
        if (!session && state.chatGrouplist.length > 0) {
          session = state.chatGrouplist[0]
          state.selectGroupId = state.chatGrouplist[0].id
        }
        console.log(session);

        return session
      }
    },
    // 通过当前选择是哪个好友匹配相应的好友
    selectedFriend (state) {
        let friend = state.selectFriend
        
    //    let friend = state.friendlist.find(friend => friend.id === state.selectFriendId);
    //    debugger
       return friend
    },
    messages (state) {
      if (state.model == 1) {
        let session = state.chatlist.find(session => session.id === state.selectId);
        return session ? session.messages : []
      } else {
        let session = state.chatGrouplist.find(session => session.id === state.selectGroupId);
        return session ? session.messages : []
      }
    }
}

const actions = {
	search: ({ commit }, value) => {
        setTimeout(() => {
                commit('search', value)
        }, 100)
    },
    selectSession: ({ commit }, value) => {
      commit('selectSession', value.id)
      commit('toMemberId', value.memberId)
    },
    selectGroupSession: ({ commit }, value) => {
      commit('selectGroupSession', value.id)
      commit('selectGroupName', value.groupName)
      commit('toGroupId', value.id)
    },
    selectFriend: ({ commit }, value) => commit('selectFriend', value),
    sendMessage: ({ commit }, msg) => {
      commit('sendMessage', msg)
    },
    chatType: ({ commit }, type) => {
      commit('chatType', type)
    },
    groupList: ({ commit }, groupList) => {
      commit('groupList', groupList)
    },
    receiveOfflineMessage: ({ commit }, arr) => {
      commit('receiveOfflineMessage', arr)
    },
    send: ({ commit }) => commit('send'),
    initData: ({ commit }) => commit('initData')
}
const store = new Vuex.Store({
  state,
  mutations,
  getters,
  actions
})

// 监听聊天列表的值， 发生变化就保存在localStorage中
store.watch(
    (state) => state.chatlist,
    (val) => {      
        localStorage.setItem('vue-chat', JSON.stringify(val));
    },
    {
        deep: true
    }
)

store.watch(
    (state) => state.chatGrouplist,
    (val) => {      
        localStorage.setItem('vue-chat-group', JSON.stringify(val));
    },
    {
        deep: true
    }
)
export default store;
